<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;
use Goods\Entity\GoodsBrand;
use Goods\Entity\GoodsClass;
use Goods\Form\GoodsBrandForm;
use Goods\Service\GoodsBrandInClassManager;
use Goods\Service\GoodsBrandManager;
use Goods\Service\GoodsManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;

class GoodsBrandController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $goodsBrandManager;
    private $goodsManager;
    private $goodsBrandInClassManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager,
        GoodsBrandManager $goodsBrandManager,
        GoodsManager    $goodsManager,
        GoodsBrandInClassManager $goodsBrandInClassManager
    )
    {
        $this->translator           = $translator;
        $this->entityManager        = $entityManager;
        $this->goodsBrandManager    = $goodsBrandManager;
        $this->goodsManager         = $goodsManager;
        $this->goodsBrandInClassManager = $goodsBrandInClassManager;
    }

    /**
     * 商品品牌列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $brandList = $this->entityManager->getRepository(GoodsBrand::class)->findAllBrand();

        return ['brandList' => $brandList];
    }

    /**
     * 添加商品品牌
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);

        $form = new GoodsBrandForm();
        $form->get('inClassId')->setValueOptions($this->goodsPlugin()->classValueArray($classList));

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $goodsBrand = $this->goodsBrandManager->addGoodsBrand($data);
                if (isset($data['inClassId']) && !empty($data['inClassId'])) $this->goodsBrandInClassManager->addBrandInClass($data['inClassId'], $goodsBrand->getBrandId());

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('品牌 %s 添加成功!'), $data['brandName']), $this->translator->translate('商品品牌'));

                return $this->redirect()->toRoute('goods-brand');
            }
        }

        return [
            'form'      => $form,
            'classList' => $classList
        ];
    }

    /**
     * 编辑商品品牌
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $brandId = (int) $this->params()->fromRoute('id', -1);

        $brandInfo = $this->entityManager->getRepository(GoodsBrand::class)->findOneByBrandId($brandId);
        if($brandInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该品牌不存在!'));
            return $this->redirect()->toRoute('goods-brand');
        }

        //商品分类
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findBy([], ['classTopId' => 'ASC', 'classSort' => 'ASC']);
        $classList  = Common::classOptions($goodsClass);

        $form = new GoodsBrandForm($brandInfo);
        $form->get('inClassId')->setValueOptions($this->goodsPlugin()->classValueArray($classList));

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $this->goodsBrandManager->editGoodsBrand($data, $brandInfo);
                $this->goodsBrandInClassManager->editGoodsBrandInClass($data['inClassId'], $brandId);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('品牌 %s 编辑成功!'), $data['brandName']), $this->translator->translate('商品品牌'));

                return $this->redirect()->toRoute('goods-brand');
            }
        } else $form->setData($brandInfo->valuesArray());

        $query      = $this->entityManager->getRepository(Goods::class)->findBrandGoods($brandId);
        $paginator  = $this->adminCommon()->shopPaginator($query, 1);

        //已选的商品分类
        $selectedClass = $this->goodsPlugin()->selectedGoodsBrandInClassArray($brandId);

        return [
            'form' => $form,
            'brandInfo' => $brandInfo,
            'goodsList' => $paginator,
            'classList' => $classList,
            'selectedClass' => $selectedClass
        ];
    }

    /**
     * 删除商品品牌
     * @return \Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $brandId = (int) $this->params()->fromRoute('id', -1);

        $brandInfo = $this->entityManager->getRepository(GoodsBrand::class)->findOneByBrandId($brandId);
        if($brandInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该品牌不存在!'));
            return $this->redirect()->toRoute('goods-brand');
        }

        $this->goodsBrandManager->deleteGoodsBrand($brandInfo);
        $this->adminCommon()->deleteImage($brandInfo->getBrandLogo());
        $this->goodsBrandInClassManager->delGoodsBrandInClass($brandId);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('品牌 %s 删除成功!'), $brandInfo->getBrandName()), $this->translator->translate('商品品牌'));

        return $this->adminCommon()->toReferer();
    }

    /**
     * 品牌商品的分页ajax显示
     * @return ViewModel
     */
    public function ajaxBrandGoodsAction()
    {
        $view = new ViewModel();
        $view->setTerminal(true);

        $brandId= (int) $this->params()->fromRoute('id', -1);
        $page   = (int) $this->params()->fromQuery('page', 1);
        $query      = $this->entityManager->getRepository(Goods::class)->findBrandGoods($brandId);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return $view->setVariables(['brandId' => $brandId, 'goodsList' => $paginator]);
    }

    /**
     * 将商品中的品牌id设置为0
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteBrandGoodsAction()
    {
        $goodsId    = (int) $this->params()->fromRoute('id', -1);
        $goodsInfo  = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($goodsId);
        if($goodsInfo == null) return new JsonModel(['msg' => $this->translator->translate('该品牌商品不存')]);
        $this->goodsManager->editGoods(['brandId' => 0], $goodsInfo);
        return new JsonModel(['state' => 'ok']);
    }

    /**
     * 批量处理排序
     * @return mixed
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateAllSortAction()
    {
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            if(!empty($data['brandSort'])) {
                $this->goodsBrandManager->updateAllBrandSort($data);

                $this->adminCommon()->addOperLog($this->translator->translate('批量排序处理成功!'), $this->translator->translate('商品品牌'));
            }
        }

        return $this->adminCommon()->toReferer();
    }
}